package com.ym.pms.security.handler;

import com.alibaba.fastjson.JSON;
import com.ym.pms.config.Constants;
import com.ym.pms.security.entity.SysUserDetails;
import com.ym.pms.utils.AccessAddressUtils;
import com.ym.pms.utils.JSONResult;
import com.ym.pms.security.utils.JWTTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 11:27 2020/12/21
 * @Modified:
 */
@Component
@Slf4j
public class UserLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        SysUserDetails sysUserDetails = (SysUserDetails) authentication.getPrincipal();
        String ip = AccessAddressUtils.getIpAddress(httpServletRequest);
        sysUserDetails.setIp(ip);
        String token = JWTTokenUtil.createAccessToken(sysUserDetails);

        // 保存Token信息到Redis中
        JWTTokenUtil.setTokenInfo(token, sysUserDetails.getUsername(), ip);

        log.info("用户{}登录成功，Token信息已保存到Redis", sysUserDetails.getUsername());

        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(JSON.toJSONString(JSONResult.build(200, "登录成功", tokenMap)));
    }
}
